package com.tyk.bookstore.front.auth.strategy.impl;

import com.tyk.bookstore.front.auth.model.entity.MemberDo;
import com.tyk.bookstore.front.auth.model.query.LoginPwdQuery;
import com.tyk.bookstore.front.auth.repository.MemberAuthRepository;
import com.tyk.bookstore.front.auth.strategy.LoginAction;
import com.tyk.bookstore.front.auth.util.ParamUtil;
import com.tyk.bookstore.front.common.core.model.result.CommonResultEnum;
import com.tyk.bookstore.front.common.core.util.AssertUtil;
import com.tyk.bookstore.front.common.dal.mapper.dto.SinDto;
import com.tyk.bookstore.front.common.other.code.behavior.manager.BehaviorCodeManager;
import com.tyk.bookstore.front.common.other.code.behavior.model.enume.SceneType;
import com.tyk.bookstore.front.member.model.result.MemberResultEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

@Component
@RequiredArgsConstructor
public class EmailPwdLoginAction implements LoginAction<LoginPwdQuery> {
    private final MemberAuthRepository memberAuthRepository;
    private final BehaviorCodeManager behaviorCodeManager;

    @Override
    public boolean check(LoginPwdQuery query) {
        return ParamUtil.checkEmail(query.getPrincipal()) && ParamUtil.checkPassword(query.getCertificate());
    }

    @Override
    public Long getMemberId(LoginPwdQuery query) {

        // 校验行为验证码
        boolean check = behaviorCodeManager.check(SceneType.LOGIN, query.getVerifyParam());
        AssertUtil.isTrue(check, CommonResultEnum.CODE_BEHAVIOR_ERROR);

        // 校验邮箱
        SinDto<BigInteger> dto = memberAuthRepository.selectSin1Eq(
                MemberDo::getId, MemberDo::getEmail, query.getPrincipal(), MemberDo.class
        );
        AssertUtil.notNull(dto, MemberResultEnum.EMAIL_NOT_BOUND);

        // 返回会员ID
        return dto.getV1().longValue();

    }
}
